/**
 * 
 */
package com.geekteam.geometrychess.handler.request.game;

import com.geekteam.geometrychess.extension.ChessExtension;
import com.geekteam.geometrychess.game.entity.Location;
import com.geekteam.geometrychess.game.entity.SimplePiece;
import com.geekteam.geometrychess.handler.request.BaseRequestHandler;
import com.geekteam.geometrychess.utils.Code;
import com.geekteam.geometrychess.utils.Commands;
import com.geekteam.geometrychess.utils.Constants.Key;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;

/**
 * @author MtRol
 *
 */
public class MoveRequestHandler extends BaseRequestHandler{

	@Override
	public void handleClientRequest(User user, ISFSObject params) {
		mRoom = user.getLastJoinedRoom();
		mExtension = (ChessExtension) getParentExtension();
		mGameBoard = mExtension.getBoard(mRoom.getId());
		
		if(!mRoom.isGame()){
			mExtension.sendPrivateError(Code.ROOM_NOT_GAME, "room not game", user.getId());
			return;
		}
		
		if(mGameBoard==null){
			mExtension.sendPrivateError(Code.GAME_BOARD_NULL, "game board null", user.getId());
			return;
		}
		
		if(mGameBoard.getRoomBoard().isPlaying()){
			mExtension.sendPrivateError(Code.GAME_NOT_PLAYING, "game not playing", user.getId());
			return;
		}
		
		if(!mGameBoard.getRoomBoard().isTurn(user.getId())){
			mExtension.sendPrivateError(Code.PLAYER_NOT_TURN, "player not turn", user.getId());
			return;
		}
		
		int idPiece = params.getInt(Key.ID_PIECE);
		int targetPosX = params.getInt(Key.TARGET_POS_X);
		int targetPosY = params.getInt(Key.TARGET_POS_Y);
		
		Location targetLocation = new Location(targetPosX, targetPosY);
		SimplePiece piece = (SimplePiece) mGameBoard.getChessBoard().getPieceById(idPiece);
		int currentPosX = piece.getLocation().getPosX();
		int currentPosY = piece.getLocation().getPosY();
		//move success
		if(mGameBoard.getChessBoard().tryMove(piece, targetLocation)){
			//TODO check geometry here
			
			mResultObject = new SFSObject();
			mResultObject.putInt(Key.CODE, Code.SUCCESS);
			mResultObject.putInt(Key.ID_PIECE, idPiece);
			mResultObject.putInt(Key.TARGET_POS_X, targetPosX);
			mResultObject.putInt(Key.TARGET_POS_Y, targetPosY);
			mResultObject.putInt(Key.CURRENT_POS_X, currentPosX);
			mResultObject.putInt(Key.CURRENT_POS_Y, currentPosY);
			mResultObject.putInt(Key.USER_MOVE, user.getId());
			//TODO put point, number geometry, type geometry to move here
			
			send(Commands.MOVE, mResultObject, mRoom.getUserList());
		}else{
			mExtension.sendPrivateError(Code.CANT_MOVE_TO, "you cant move to ("+targetPosX+", "+targetPosY+")", user.getId());
			return;
		}
	}

}
